import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {Button, Card, Form, Input, Modal, Radio,} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

const RadioGroup = Radio.Group;
const {TextArea} = Input;
const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({process, loading}) => ({
  process,
  loading: loading.models.process,
  submitting: loading.effects['process/update'],
}))
@Form.create()
class process extends PureComponent {
  handleSubmit = e => {
    const {dispatch, form, submitting} = this.props;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.update(values)
      }
    });
  };

  state = {
    noDefault: '无',
    optionsList:[],
  };

  //查询重置
  handleFormReset = (dataList) => {
    const {form, dispatch} = this.props;
    this.setState({
      noDefault: '',
    });

    Modal.confirm({
      title: '重置',
      content: '您确定重置吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.resetProcess(dataList),
    });

  };
  /**
   * 重置流程策略
   */
  resetProcess = (dataList) => {
    const {dispatch} = this.props;
    if (dataList && dataList.length) {
      let obj = {};
      dataList.map((v, i) => {
        let stringId = 'dataDictUpdateFormList[' + i + '].id';
        let stringName = 'dataDictUpdateFormList[' + i + '].dataDictName';
        obj[stringId] = v.dataDictId;
        obj[stringName] = '无';
      });

      dispatch({
        type: 'process/update',
        payload: obj,
        callback: (res) => {
          if (res.result == "ok") {
            Modal.success({title: res.msg});
            dispatch({
              type: 'process/query',
            });
            this.props.form.resetFields();
          } else {
            Modal.error({title: '操作失败', content: res.msg});
          }
        },
      });

    } else {
      Modal.error({title: '操作失败', content: "缺少操作配置"});
    }


  }

  // 提交
  update(value) {
    const {dispatch} = this.props;
    const list = [];
    let obj = {};
    for (var name in value) {
      list.push({
        id: name,
        dataDictName: value[name]
      })
    }
    list.map((v, i) => {
      let stringId = 'dataDictUpdateFormList[' + i + '].id';
      let stringName = 'dataDictUpdateFormList[' + i + '].dataDictName';
      obj[stringId] = v.id;
      obj[stringName] = v.dataDictName;
    });
    dispatch({
      type: 'process/update',
      payload: obj,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'process/query',
          });
          this.props.form.resetFields();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  componentDidMount() {
    // 页面初始化
    const {dispatch} = this.props;
    dispatch({
      type: 'process/query',
    });
  }


  render() {
    const {
      form: {getFieldDecorator, getFieldValue},
      process: {data: {dataList}},
      submitting,
    } = this.props;


    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    let arrys = [];

    dataList && dataList.map((item, index) => {
      //其中一组，比如下载
      const voList = item.processStrategyTypeVoList;
      let selectValue = "无";
      let plainOptions = [];
      voList && voList.map((item, index) => {
        //下载内的选项,value就是展示的选项，因此，平铺开，const plainOptions = ['Apple', 'Pear', 'Orange'];

        plainOptions.push(item.dataDictName);
        if (item.checkedFlag) {
          selectValue = item.dataDictName;
        }
      })
      console.info("item index:" + index + "---value :" + selectValue);
      arrys.push(<FormItem key={item.dataDictId} {...formItemLayout} label={item.dataDictName}>
        {getFieldDecorator(item.dataDictId.toString(), {initialValue: selectValue})(
          <RadioGroup options={plainOptions}/>
        )}
      </FormItem>)

    })


    // dataList && dataList.map((item, index) => {
    //   const voList = item.processStrategyTypeVoList;
    //   const newListReturn = arrToNewArr(voList, 'dataDictName', 'checkedFlag');
    //   arrys.push(<FormItem key={item.dataDictId} {...formItemLayout} label={item.dataDictName}>
    //     {getFieldDecorator(item.dataDictId.toString(), {initialValue: newListReturn.b || ''})(
    //       <RadioGroup options={newListReturn.a} value={newListReturn.b}/>
    //     )}
    //   </FormItem>)
    //
    // })


    return (
      <PageHeaderWrapper title="流程策略">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{marginTop: 8}}>
            {arrys}
            {dataList ?
              <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                <Button type="primary" htmlType="submit" onSubmit={this.handleSubmit} loading={submitting}>
                  提交
                </Button>
                <Button style={{marginLeft: 8}} onClick={() => this.handleFormReset(dataList)}>
                  重置
                </Button>
              </FormItem>
              : null}
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default process;
